package com.item.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author zhang-rongyao
 * @version V1.0
 * @Package com.item.model.filter
 * @date 2021/7/26 10:04
 */
public class HttpServletFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        if (request instanceof HttpServletRequest) {
            String method = ((HttpServletRequest) request).getMethod();
            if ("POST".equals(method)) {
                //包装成自定义的Request, 就可以多次的获取
                String contentType = request.getContentType();
                if (contentType.contains("application/x-www-form-urlencoded")) {
                    //post 表单提交方式
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    requestWrapper = new ParameterRequestWrapper((HttpServletRequest) request, parameterMap);
                } else if (contentType.contains("application/json")) {
                    //post json提交的方式
                    requestWrapper = new RequestWrapper((HttpServletRequest) request);
                }
            }
        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {

    }
}
